/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package CL;

import EL.Accounts;
import EL.Foods;
import EL.OrderDetails;
import EL.OrderDetailsPK;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import sfsBeans.ShoppingCartBLORemote;
import slsBeans.FoodBLORemote;
import slsBeans.OrderBLORemote;

/**
 *
 * @author Tian
 */
public class OrderCO extends HttpServlet
{

    private OrderBLORemote rOrder;
    private FoodBLORemote rFood;
    private ShoppingCartBLORemote rShoppingCart;

    @Override
    public void init() throws ServletException
    {
        try
        {
            super.init();
            String jndiFileName = this.getServletContext().getRealPath("/") + "/WEB-INF/jndi.properties";
            Properties props = new Properties();
            props.load(new FileInputStream(jndiFileName));
            InitialContext ctx = new InitialContext(props);
            rOrder = (OrderBLORemote) ctx.lookup("OrderBLO/remote");
            rFood = (FoodBLORemote) ctx.lookup("FoodBLO/remote");
            rShoppingCart = (ShoppingCartBLORemote) ctx.lookup("ShoppingCartBLO/remote");
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        String action = request.getParameter("action");

        if (action.equalsIgnoreCase("add2Cart"))
        {
            HttpSession session = request.getSession();
            Accounts account = (Accounts) session.getAttribute("acc");
            if (account != null)
            {
                String foodID = request.getParameter("id");
                String quantity = request.getParameter("quantity");
                OrderDetailsPK pk = new OrderDetailsPK("", Integer.parseInt(foodID));
                OrderDetails oDetail = new OrderDetails(pk);
                oDetail.setFoods(rFood.getByID(Integer.parseInt(foodID)));
                oDetail.setQuantity(Integer.parseInt(quantity));
                rShoppingCart.addFood2Cart(oDetail);

                ArrayList<OrderDetails> foodCart = rShoppingCart.viewFoodCart();
                session.setAttribute("foodCart", foodCart);
                response.sendRedirect("OrderCO?action=viewCart");
            }
        }
        else if (action.equalsIgnoreCase("viewCart"))
        {
            HttpSession session = request.getSession();
            ArrayList<OrderDetails> foodCart = (ArrayList<OrderDetails>) session.getAttribute("foodCart");
            float total = 0;
            for (OrderDetails orderDetail : foodCart)
            {
                total += orderDetail.getQuantity() * orderDetail.getFoods().getPrice();
            }
            session.setAttribute("total", total);
            session.setAttribute("foodCart", foodCart);
            response.sendRedirect("us_ViewCart.jsp");
        }
        else if (action.equalsIgnoreCase("pay"))
        {
            String hNumber = request.getParameter("txtNumber");
            String street = request.getParameter("txtStreet");
            String ward = request.getParameter("txtWard");
            String district = request.getParameter("txtDistrict");
            String city = request.getParameter("txtCity");
            String phone = request.getParameter("txtPhone");
            HttpSession session = request.getSession();
            ArrayList<OrderDetails> foodCart = (ArrayList<OrderDetails>) session.getAttribute("foodCart");
            for(OrderDetails od : foodCart)
            {
                od.setNumber(hNumber); od.setStreet(street); od.setWard(ward); od.setDistrict(district); od.setCity(city);
                od.setPhone(phone);
            }
            Accounts account = (Accounts) session.getAttribute("acc");
            String result = rOrder.add(account, foodCart);
            if(!result.equals(""))
            {
                request.setAttribute("orderID", result);
                RequestDispatcher rd = request.getRequestDispatcher("us_OrderSuccess.jsp");
                rd.forward(request, response);
            }
        }
        else if (action.equalsIgnoreCase("update"))
        {
            HttpSession session = request.getSession();
            ArrayList<OrderDetails> foodCart = (ArrayList<OrderDetails>) session.getAttribute("foodCart");
            Enumeration params = request.getParameterNames();

            System.out.println(params.toString());
            while (params.hasMoreElements())
            {
                String paraName = (String) params.nextElement();
                String paraValue = request.getParameter(paraName);
                if (paraName.contains("txtQuantity") && !paraValue.equals("0"))
                {
                    int foodID = Integer.parseInt(paraName.split("_")[0]);
                    int quantity = Integer.parseInt(paraValue);
                    Foods f = rFood.getByID(foodID);
                    for (OrderDetails orderDetail : foodCart)
                    {
                        if (orderDetail.getFoods().equals(f))
                        {
                            orderDetail.setQuantity(quantity);
                            System.out.println("so luong = "+orderDetail.getQuantity());
                            rShoppingCart.update(orderDetail);
                        }
                    }
                }
            }
            foodCart = rShoppingCart.viewFoodCart();
            session.setAttribute("foodCart", foodCart);
            response.sendRedirect("OrderCO?action=viewCart");
        }
        else if(action.equalsIgnoreCase("delete"))
        {
            HttpSession session = request.getSession();
            ArrayList<OrderDetails> foodCart = (ArrayList<OrderDetails>) session.getAttribute("foodCart");
            String foodId = request.getParameter("id");
            Foods f = rFood.getByID(Integer.parseInt(foodId));
            for(OrderDetails orderDetail : foodCart)
            {
                if(orderDetail.getFoods().equals(f))
                {
                    rShoppingCart.remove(orderDetail);
                }
            }
            foodCart = rShoppingCart.viewFoodCart();
            session.setAttribute("foodCart", foodCart);
            response.sendRedirect("OrderCO?action=viewCart");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "Short description";
    }// </editor-fold>
}
